package com.lhl.jwt.security.config;

import com.lhl.jwt.security.filter.MiniAppAuthenticationFilter;
import com.lhl.jwt.security.handler.JwtAuthenticationFailureHandler;
import io.swagger.annotations.Api;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;

/**
 * @className: com.lhl.jwt.security.config.MiniAppAuthenticationConfigurer
 * @description: TODO 类描述
 * @author: king
 * @date: 2020-12-21 17:43
 **/
@Api(tags = "MiniAppAuthenticationConfigurer", produces = "MiniAppAuthenticationConfigurer")
public class MiniAppAuthenticationConfigurer<T extends MiniAppAuthenticationConfigurer<T, B>, B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T, B> {
    private MiniAppAuthenticationFilter miniAppAuthenticationFilter;

    public MiniAppAuthenticationConfigurer() {
        miniAppAuthenticationFilter = new MiniAppAuthenticationFilter();
    }
    @Override
    public void configure(B builder) throws Exception {
        miniAppAuthenticationFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        miniAppAuthenticationFilter.setAuthenticationFailureHandler(new JwtAuthenticationFailureHandler());

        miniAppAuthenticationFilter = postProcess(miniAppAuthenticationFilter);
        //这里将该过滤器放在logout 后面 是因为会判断前面的login和logout 中的token
        builder.addFilterAfter(miniAppAuthenticationFilter, LogoutFilter.class);
    }

    /**
     * 设置认证成功后的操作
     * @param successHandler
     * @return
     */
    public MiniAppAuthenticationConfigurer<T, B> authenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
        miniAppAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        return this;
    }

    /**
     * 设置认证成功后的操作
     * @param failureHandler
     * @return
     */
    public MiniAppAuthenticationConfigurer<T, B> authenticationFailureHandler(JwtAuthenticationFailureHandler failureHandler) {
        miniAppAuthenticationFilter.setAuthenticationFailureHandler(failureHandler);
        return this;
    }
}
